<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="K8s," />




  


  <link rel="alternate" href="/atom.xml" title="Richey's Blog" type="application/atom+xml" />






<meta name="description" content="比较容器和虚拟机和虚拟机相比容器更加轻量级，因为每个虚拟机需要运行自己的一组系统进程，而容器只是运行在宿主机上被隔离的单个进程。 虚拟机的好处是它们提供完全隔离的环境，因为每个虚拟机都运行在它们自己的Linux内核上，而容器则是调用同一个内核。 那容器是如何实现隔离的呢？有两个机制可用：  Linux命名空间它使每个进程只看到自己的系统视图（文件、进程、网络端口、主机名等） Linux控制组（c">
<meta property="og:type" content="article">
<meta property="og:title" content="Kubernetes02-核心概念">
<meta property="og:url" content="http://10000hours.top/2021/05/12/Kubernetes02-%E6%A0%B8%E5%BF%83%E6%A6%82%E5%BF%B5/index.html">
<meta property="og:site_name" content="Richey&#39;s Blog">
<meta property="og:description" content="比较容器和虚拟机和虚拟机相比容器更加轻量级，因为每个虚拟机需要运行自己的一组系统进程，而容器只是运行在宿主机上被隔离的单个进程。 虚拟机的好处是它们提供完全隔离的环境，因为每个虚拟机都运行在它们自己的Linux内核上，而容器则是调用同一个内核。 那容器是如何实现隔离的呢？有两个机制可用：  Linux命名空间它使每个进程只看到自己的系统视图（文件、进程、网络端口、主机名等） Linux控制组（c">
<meta property="og:image" content="http://assets.processon.com/chart_image/5c75503fe4b0f9fba693aa6b.png">
<meta property="og:image" content="https://blog-pic-1254088127.picsh.myqcloud.com/k8s-yaml-metadata.png">
<meta property="og:image" content="https://blog-pic-1254088127.picsh.myqcloud.com/k8s-yaml-spec01.png">
<meta property="og:image" content="https://blog-pic-1254088127.picsh.myqcloud.com/k8s-svc-yaml.png">
<meta property="og:image" content="https://blog-pic-1254088127.picsh.myqcloud.com/k8s-endpoints.png">
<meta property="og:image" content="http://assets.processon.com/chart_image/5c75503fe4b0f9fba693aa53.png">
<meta property="og:image" content="http://assets.processon.com/chart_image/5c75517be4b0f0908aa32b64.png">
<meta property="og:image" content="https://blog-pic-1254088127.picsh.myqcloud.com/k8s-ingress-yaml.png">
<meta property="og:image" content="http://assets.processon.com/chart_image/5c75503fe4b0f9fba693aa73.png">
<meta property="og:image" content="https://blog-pic-1254088127.picsh.myqcloud.com/k8s-health-http.png">
<meta property="og:image" content="https://blog-pic-1254088127.picsh.myqcloud.com/k8s-rs-01.png">
<meta property="article:published_time" content="2021-05-11T16:00:00.000Z">
<meta property="article:modified_time" content="2021-06-12T10:56:14.730Z">
<meta property="article:author" content="Richey Liu">
<meta property="article:tag" content="K8s">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://assets.processon.com/chart_image/5c75503fe4b0f9fba693aa6b.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://10000hours.top/2021/05/12/Kubernetes02-核心概念/"/>





  <title>Kubernetes02-核心概念 | Richey's Blog</title>
  








<meta name="generator" content="Hexo 4.2.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Richey's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">吾生也有涯，而知也无涯。以有涯随无涯，殆已。</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://10000hours.top/2021/05/12/Kubernetes02-%E6%A0%B8%E5%BF%83%E6%A6%82%E5%BF%B5/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Richey Liu">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Richey's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Kubernetes02-核心概念</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2021-05-12T00:00:00+08:00">
                2021-05-12
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/SRE/" itemprop="url" rel="index">
                    <span itemprop="name">SRE</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2021/05/12/Kubernetes02-%E6%A0%B8%E5%BF%83%E6%A6%82%E5%BF%B5/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/2021/05/12/Kubernetes02-%E6%A0%B8%E5%BF%83%E6%A6%82%E5%BF%B5/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          
             <span id="/2021/05/12/Kubernetes02-%E6%A0%B8%E5%BF%83%E6%A6%82%E5%BF%B5/" class="leancloud_visitors" data-flag-title="Kubernetes02-核心概念">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><img src="http://assets.processon.com/chart_image/5c75503fe4b0f9fba693aa6b.png" alt="k8s集群架构"></p>
<h1 id="比较容器和虚拟机"><a href="#比较容器和虚拟机" class="headerlink" title="比较容器和虚拟机"></a>比较容器和虚拟机</h1><p>和虚拟机相比容器更加轻量级，因为每个虚拟机需要运行自己的一组系统进程，而容器只是运行在宿主机上被隔离的单个进程。</p>
<p>虚拟机的好处是它们提供完全隔离的环境，因为每个虚拟机都运行在它们自己的Linux内核上，而容器则是调用同一个内核。</p>
<p>那容器是如何实现隔离的呢？有两个机制可用：</p>
<ol>
<li>Linux命名空间<br>它使每个进程只看到自己的系统视图（文件、进程、网络端口、主机名等）</li>
<li>Linux控制组（cgroups）<br>它限制了进程能使用的资源（cpu、内存、网络带宽等）</li>
</ol>
<h1 id="Pod"><a href="#Pod" class="headerlink" title="Pod"></a>Pod</h1><p>Kubernetes中的基本构成模块,基本操作单元。<br>一个pod就是一组紧密管理的容器（也可能是一个）,它们一起运行在一个工作节点上，及同一个Linux命名空间中。<br>一个pod就像一个独立的逻辑机器，它有独立的IP、主机名、进程等。</p>
<h2 id="区别于容器"><a href="#区别于容器" class="headerlink" title="区别于容器"></a>区别于容器</h2><p>容器被设计成每个容器中只能运行一个进程，pod中可以运行多个容器（便于相关服务部署在一起）。</p>
<p>容器间彼此完全隔离，pod中的容器可以共享相同的命名空间，可以共享相同的主机名和端口,同样的这些容器在相同的IPC命名空间下运行，因此可以使用IPC进行通信。</p>
<p>可以通过localhost与同一个pod中的其它容器进行通讯。</p>
<h2 id="平坦pod间网络"><a href="#平坦pod间网络" class="headerlink" title="平坦pod间网络"></a>平坦pod间网络</h2><p>Kubernetes集群中的所有pod都是在同一个共享网络地址空间中。所以每个pod都可以通过访问其它pod 的ip地址实现相互访问。（它们之间没有NAT）</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">kubectl get pods &#x2F;&#x2F;列出pod</span><br><span class="line">kubectl describe pod pod-name &#x2F;&#x2F;查看具体pod的详细信息</span><br><span class="line">kubectl get pod my-pode-name -o yaml &#x2F;&#x2F; 查看pod的当前yaml配置</span><br></pre></td></tr></table></figure>

<h2 id="yaml文件重要参数"><a href="#yaml文件重要参数" class="headerlink" title="yaml文件重要参数"></a>yaml文件重要参数</h2><ul>
<li>metadata<br>包括名称、命名空间、标签和关于容器的其它信息</li>
<li>spec<br>包括pod的实际说明， 例如pod的容器、卷和其它数据</li>
<li>status<br>运行中的pod的当前信息，例如pod所处的条件、每个容器的描述和状态，以及内部ip和其它信息</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">kubectl explain pod. &#x2F;&#x2F; 查看可能的api字段</span><br><span class="line">kubectl explain pod.spec</span><br></pre></td></tr></table></figure>
<h2 id="以YAML或JSON描述文件船舰pod"><a href="#以YAML或JSON描述文件船舰pod" class="headerlink" title="以YAML或JSON描述文件船舰pod"></a>以YAML或JSON描述文件船舰pod</h2><p>查看现有pod的yaml描述文件</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">root@node1:&#x2F;home&#x2F;richey# kubectl get pod kubia-6wgzj -o yaml</span><br></pre></td></tr></table></figure>
<p><img src="https://blog-pic-1254088127.picsh.myqcloud.com/k8s-yaml-metadata.png" alt="k8s-yaml-metadata"></p>
<p><img src="https://blog-pic-1254088127.picsh.myqcloud.com/k8s-yaml-spec01.png" alt="k8s-yaml-spec01"></p>
<h2 id="访问pod"><a href="#访问pod" class="headerlink" title="访问pod"></a>访问pod</h2><p>pod有自己的IP，但是这个ip是集群内部的，不能从集群外部访问。</p>
<p>需要创建服务对象公开pod，服务对象是一个特殊的LoadBalanceer类型的服务，可以通过服务对外共该的ip访问pod。</p>
<h1 id="服务"><a href="#服务" class="headerlink" title="服务"></a>服务</h1><p>pod通常需要对来自集群内部的其它pod，以及来自集群外部的http请求作出响应。</p>
<p>pod需要一种寻找其它pod的方法来使用其它pod提供的服务，service就是用来做这件事的。</p>
<p>service服务是一种为一组功能相同的pod提供单一不变接入点的资源，当服务存在时它的ip和端口不会变。</p>
<p>服务对pod的请求是负载均衡的。</p>
<h2 id="列出所有服务"><a href="#列出所有服务" class="headerlink" title="列出所有服务"></a>列出所有服务</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">kubectl get svc &#x2F;&#x2F;列出所有服务，-o wide 可查看详细数据</span><br><span class="line">&#x2F;&#x2F; 详细数据中的EXTERNAL-IP 是对外开放的ip</span><br></pre></td></tr></table></figure>

<h2 id="通过kubectl-expose创建服务"><a href="#通过kubectl-expose创建服务" class="headerlink" title="通过kubectl expose创建服务"></a>通过kubectl expose创建服务</h2><h2 id="通过YAML描述文件创建服务"><a href="#通过YAML描述文件创建服务" class="headerlink" title="通过YAML描述文件创建服务"></a>通过YAML描述文件创建服务</h2><p>创建kubia-svc.yaml文件</p>
<p><img src="https://blog-pic-1254088127.picsh.myqcloud.com/k8s-svc-yaml.png" alt="k8s-svc-yaml"></p>
<p>使用kubectl create 创建service</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">kubectl create -f kubia-svc.yaml</span><br><span class="line">service&#x2F;kubia created</span><br><span class="line">root@node1:&#x2F;opt&#x2F;yaml&#x2F;demo# kubectl get svc</span><br><span class="line">NAME         TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)   AGE</span><br><span class="line">kubernetes   ClusterIP   10.96.0.1       &lt;none&gt;        443&#x2F;TCP   4d16h</span><br><span class="line">kubia        ClusterIP   10.111.170.56   &lt;none&gt;        80&#x2F;TCP    6s</span><br></pre></td></tr></table></figure>

<p>可以发现新的kubia服务已经被分配了一个内部的集群ip，因为只有集群内部ip，所以只能在集群内被访问。</p>
<h2 id="在已有的pod中运行命令请求service"><a href="#在已有的pod中运行命令请求service" class="headerlink" title="在已有的pod中运行命令请求service"></a>在已有的pod中运行命令请求service</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">root@node1:&#x2F;opt&#x2F;yaml&#x2F;demo# kubectl exec kubia-6wgzj -- curl -s http:&#x2F;&#x2F;10.111.170.56</span><br><span class="line">You&#39;ve hit kubia-6wgzj</span><br></pre></td></tr></table></figure>
<blockquote>
<p>– 代表kubectl命令的结束。两个横杠之后是要要pod内部执行的命令，如果要执行的命令没有以横杠开始的参数，双横杠也不是必须的</p>
</blockquote>
<h2 id="设置服务上的会话亲和性"><a href="#设置服务上的会话亲和性" class="headerlink" title="设置服务上的会话亲和性"></a>设置服务上的会话亲和性</h2><p>默认情况下服务会将请求随机执行pod中任意一个，即使请求来自同一个客户端。</p>
<p>如果我们希望特定客户端的请求每次都指向同一个pod，可以设置服务的sessionAffinity属性为ClientIP（而不是None，None是默认值）。</p>
<p>Kubernetes仅支持None和ClientIP两种形式的会话亲和性，不支持cookie的会话亲和性选项，因为Kubernetes的服务基于4层网络协议，不在HTTP层面工作。</p>
<h2 id="同一个服务暴露多个端口"><a href="#同一个服务暴露多个端口" class="headerlink" title="同一个服务暴露多个端口"></a>同一个服务暴露多个端口</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">apiVersion: v1</span><br><span class="line">kind: Service</span><br><span class="line">metadata:</span><br><span class="line">    name: kubia</span><br><span class="line">spec:</span><br><span class="line">    #sessionAffinity: ClientIP</span><br><span class="line">    ports:</span><br><span class="line">    - name: http</span><br><span class="line">      port: 80</span><br><span class="line">      targetPort: 8080</span><br><span class="line">    - name: https</span><br><span class="line">      port: 443</span><br><span class="line">      targetPort: 8443</span><br><span class="line">    selector:</span><br><span class="line">      run: kubia</span><br></pre></td></tr></table></figure>

<p>在创建一个有多个端口的服务时，必须给端口指定名字。</p>
<h2 id="服务发现"><a href="#服务发现" class="headerlink" title="服务发现"></a>服务发现</h2><h3 id="通过环境变量发现服务"><a href="#通过环境变量发现服务" class="headerlink" title="通过环境变量发现服务"></a>通过环境变量发现服务</h3><p>pod启动时Kubernetes会初始化一系列的环境变量指向现在存在的服务，如果service早于pod创建，则pod上的<br>进程可以根据环境变量获得服务的ip和port</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">root@node1:&#x2F;opt&#x2F;yaml&#x2F;demo# kubectl get pods</span><br><span class="line">NAME          READY   STATUS    RESTARTS   AGE</span><br><span class="line">kubia-6wgzj   1&#x2F;1     Running   1          3d16h</span><br><span class="line">kubia-j7q4s   1&#x2F;1     Running   0          167m</span><br><span class="line">kubia-rxndz   1&#x2F;1     Running   0          167m</span><br><span class="line">root@node1:&#x2F;opt&#x2F;yaml&#x2F;demo# kubectl delete pod --all</span><br><span class="line">pod &quot;kubia-6wgzj&quot; deleted</span><br><span class="line">pod &quot;kubia-j7q4s&quot; deleted</span><br><span class="line">pod &quot;kubia-rxndz&quot; deleted</span><br><span class="line">root@node1:&#x2F;opt&#x2F;yaml&#x2F;demo# kubectl get pod</span><br><span class="line">NAME          READY   STATUS        RESTARTS   AGE</span><br><span class="line">kubia-6vf4l   1&#x2F;1     Running       0          32s</span><br><span class="line">kubia-97c5t   1&#x2F;1     Running       0          32s</span><br><span class="line">kubia-wk7b4   1&#x2F;1     Running       0          32s</span><br><span class="line">root@node1:&#x2F;opt&#x2F;yaml&#x2F;demo# kubectl exec kubia-6vf4l env</span><br><span class="line">...</span><br><span class="line">KUBIA_SERVICE_PORT&#x3D;80</span><br><span class="line">KUBIA_SERVICE_HOST&#x3D;10.99.41.214</span><br><span class="line">...</span><br></pre></td></tr></table></figure>
<h3 id="通过DNS发现服务"><a href="#通过DNS发现服务" class="headerlink" title="通过DNS发现服务"></a>通过DNS发现服务</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">root@node1:&#x2F;opt&#x2F;yaml&#x2F;demo# kubectl get pods -n kube-system |grep coredns</span><br><span class="line">coredns-bccdc95cf-2jznl         0&#x2F;1     Running       137        3d16h</span><br><span class="line">coredns-bccdc95cf-zv7vs         1&#x2F;1     Running       1          3d16h</span><br></pre></td></tr></table></figure>

<p>k8s集群的系统命名空间下默认启动了运行dns服务的pod，在集群中的其它pod都会默认你使用其作为dns（Kubeernetes通过修改每个容器的/etc/resolv.conf文件实现）。</p>
<p>运行在pod上的进程DNS查询都会在K8s自身的DNF服务响应，该服务知道系统中运行的所有服务.</p>
<p>pod是否使用内部的DNS服务器是根据pod中spec的dnsPolicy属性决定的</p>
<h3 id="通过FQDN（全限定域名）连接服务"><a href="#通过FQDN（全限定域名）连接服务" class="headerlink" title="通过FQDN（全限定域名）连接服务"></a>通过FQDN（全限定域名）连接服务</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">kubectl exec kubia-6vf4l -- curl -s http:&#x2F;&#x2F;kubia.default.svc.cluster.local</span><br></pre></td></tr></table></figure>

<p>kubia是服务名，default是命名空间，svc.cluster.local是在所有集群本地服务名称中使用的可配置集群域后缀。</p>
<h3 id="无法ping通服务ip"><a href="#无法ping通服务ip" class="headerlink" title="无法ping通服务ip"></a>无法ping通服务ip</h3><p>服务的ip是一个虚拟ip，只有与服务端口结合时才有意义，这个ip是无法ping通的。</p>
<h2 id="endpoint-可解决访问集群外服务"><a href="#endpoint-可解决访问集群外服务" class="headerlink" title="endpoint(可解决访问集群外服务)"></a>endpoint(可解决访问集群外服务)</h2><p>服务并不是和pod直接相连的，有一种资源介于两者之间，它就是Endpoint资源。</p>
<p>运行kubectl describe svc kubia，可以看到endpoint维护了一个ip和端口的列表，当客户端连接到服务时，服务代理选择这些ip端口中的一个</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">root@node1:&#x2F;opt&#x2F;yaml&#x2F;demo# kubectl get svc</span><br><span class="line">NAME         TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)          AGE</span><br><span class="line">kubernetes   ClusterIP   10.96.0.1       &lt;none&gt;        443&#x2F;TCP          18h</span><br><span class="line">kubia        ClusterIP   10.111.206.98   &lt;none&gt;        80&#x2F;TCP,443&#x2F;TCP   19m</span><br><span class="line">root@node1:&#x2F;opt&#x2F;yaml&#x2F;demo# kubectl describe svc kubia</span><br><span class="line">Name:              kubia</span><br><span class="line">Namespace:         default</span><br><span class="line">Labels:            &lt;none&gt;</span><br><span class="line">Annotations:       &lt;none&gt;</span><br><span class="line">Selector:          run&#x3D;kubia</span><br><span class="line">Type:              ClusterIP</span><br><span class="line">IP:                10.111.206.98</span><br><span class="line">Port:              http  80&#x2F;TCP</span><br><span class="line">TargetPort:        8080&#x2F;TCP</span><br><span class="line">Endpoints:         192.169.1.21:8080,192.169.1.22:8080,192.169.2.50:8080</span><br><span class="line">Port:              https  443&#x2F;TCP</span><br><span class="line">TargetPort:        8443&#x2F;TCP</span><br><span class="line">Endpoints:         192.169.1.21:8443,192.169.1.22:8443,192.169.2.50:8443</span><br><span class="line">Session Affinity:  None</span><br><span class="line">Events:            &lt;none&gt;</span><br><span class="line">root@node1:&#x2F;opt&#x2F;yaml&#x2F;demo# kubectl get pod -o wide</span><br><span class="line">NAME          READY   STATUS    RESTARTS   AGE   IP             NODE    NOMINATED NODE   READINESS GATES</span><br><span class="line">kubia-v29qq   1&#x2F;1     Running   0          25m   192.169.1.21   node2   &lt;none&gt;           &lt;none&gt;</span><br><span class="line">kubia-xdlzm   1&#x2F;1     Running   0          25m   192.169.2.50   node3   &lt;none&gt;           &lt;none&gt;</span><br><span class="line">kubia-zblws   1&#x2F;1     Running   0          25m   192.169.1.22   node2   &lt;none&gt;           &lt;none&gt;</span><br></pre></td></tr></table></figure>
<p>查看endpoints资源</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">root@node1:&#x2F;opt&#x2F;yaml&#x2F;demo# kubectl get endpoints</span><br><span class="line">NAME         ENDPOINTS                                                           AGE</span><br><span class="line">kubernetes   172.16.250.128:6443                                                 18h</span><br><span class="line">kubia        192.169.1.21:8443,192.169.1.22:8443,192.169.2.50:8443 + 3 more...   24m</span><br></pre></td></tr></table></figure>
<h3 id="手动配置endpoint（访问外部服务的方法1）"><a href="#手动配置endpoint（访问外部服务的方法1）" class="headerlink" title="手动配置endpoint（访问外部服务的方法1）"></a>手动配置endpoint（访问外部服务的方法1）</h3><p>思考一个问题：为什么要有有一个独立的endpoint去维护ip端口列表？</p>
<p>enpoint与服务解耦后，可以分别手动配置和更新它们。</p>
<p>如果创建了不含pod选择器的服务，Kubernetes将不会创建endpoint资源，因为缺少选择器，服务也不知道应该访问哪些pod，<br>也就不知道如何创建endpoint。这种情况下可以手动创建Endpoint资源来指定服务的enpoint列表。</p>
<ol>
<li>创建没有选择器的服务</li>
</ol>
<p>external-service.yaml</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">apiVersion: v1</span><br><span class="line">kind: Service</span><br><span class="line">metadata:</span><br><span class="line">  name: external-service</span><br><span class="line">spec:</span><br><span class="line">  ports:</span><br><span class="line">  - port: 80</span><br></pre></td></tr></table></figure>
<p>创建svc</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">root@node1:&#x2F;opt&#x2F;yaml&#x2F;demo# kubectl create -f external-service.yaml</span><br><span class="line">service&#x2F;external-service created</span><br></pre></td></tr></table></figure>

<ol start="2">
<li>创建Endpoint资源</li>
</ol>
<p>external-service-endpoints.yaml</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">apiVersion: v1</span><br><span class="line">kind: Endpoints</span><br><span class="line">metadata:</span><br><span class="line">  name: external-service</span><br><span class="line">subsets:</span><br><span class="line">  - addresses:</span><br><span class="line">    - ip: 11.11.11.11</span><br><span class="line">    - ip: 22.22.22.22</span><br><span class="line">    ports:</span><br><span class="line">    - port: 80</span><br></pre></td></tr></table></figure>
<p>创建Endpoints</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">root@node1:&#x2F;opt&#x2F;yaml&#x2F;demo# kubectl create -f external-service-endpoints.yaml </span><br><span class="line">endpoints&#x2F;external-service created</span><br><span class="line">root@node1:&#x2F;opt&#x2F;yaml&#x2F;demo# kubectl get endpoints external-service</span><br><span class="line">NAME               ENDPOINTS                       AGE</span><br><span class="line">external-service   11.11.11.11:80,22.22.22.22:80   55s</span><br></pre></td></tr></table></figure>

<p><img src="https://blog-pic-1254088127.picsh.myqcloud.com/k8s-endpoints.png" alt="k8s-endpoints"></p>
<p>我们可以在不改变服务ip的情况下，去掉服务的标签选择器，修改endpoint资源，从而改变服务的实际访问。</p>
<h3 id="为外部服务创建别名（访问外部服务的方法2）"><a href="#为外部服务创建别名（访问外部服务的方法2）" class="headerlink" title="为外部服务创建别名（访问外部服务的方法2）"></a>为外部服务创建别名（访问外部服务的方法2）</h3><p>修改service的spec.type和spec.externalName后通过FQDN的方式访问服务将被代理到externalName指定的域名</p>
<p>external-service-externalname.yaml</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">appVersion: v1</span><br><span class="line">kind: Service</span><br><span class="line">metadata:</span><br><span class="line">  name: external-service</span><br><span class="line">spec:</span><br><span class="line">  type: ExternalName</span><br><span class="line">  externalName: 10000hour.top&#x2F;api</span><br><span class="line">  ports:</span><br><span class="line">  - port: 80</span><br></pre></td></tr></table></figure>

<p>如上修改后pod可以通过external-service.default.svc.cluster.local域名连接到外部服务，而不是使用实际的FQDN.</p>
<p>ExternalName服务仅在DNS级别实施，其为服务创建了简单的CNAME DNS记录，注意CNAME指向完全限定名的域名而不是数字ip地址。</p>
<h2 id="Service-type类型"><a href="#Service-type类型" class="headerlink" title="Service type类型"></a>Service type类型</h2><h3 id="ClusterIP"><a href="#ClusterIP" class="headerlink" title="ClusterIP"></a>ClusterIP</h3><p>Kubernetes 的默认服务类型。通过集群的内部 IP 暴露服务，选择该值，服务只能够在集群内部可以访问。使用ClusterIP时，如果想要对外暴露服务可以使用kube-proxy</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">apiVersion: v1</span><br><span class="line">kind: Service</span><br><span class="line">metadata:</span><br><span class="line">    name: kubia</span><br><span class="line">spec:</span><br><span class="line">    #sessionAffinity: ClientIP</span><br><span class="line">    type: ClusterIP</span><br><span class="line">    ports:</span><br><span class="line">    - name: http</span><br><span class="line">      port: 80</span><br><span class="line">      targetPort: 8080</span><br><span class="line">    selector:</span><br><span class="line">      run: kubia</span><br></pre></td></tr></table></figure>
<p>查看svc</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">root@node1:&#x2F;opt&#x2F;yaml&#x2F;demo# kubectl get svc kubia</span><br><span class="line">NAME    TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)   AGE</span><br><span class="line">kubia   ClusterIP   10.104.249.210   &lt;none&gt;        80&#x2F;TCP    83m</span><br></pre></td></tr></table></figure>
<p>10.104.249.210是集群内的一个ip，集群外是无法访问的。</p>
<h3 id="1-将服务的类型设置成NodePort"><a href="#1-将服务的类型设置成NodePort" class="headerlink" title="1.将服务的类型设置成NodePort"></a>1.将服务的类型设置成NodePort</h3><p>如果将type设置成NodePort，则会在集群的每一个节点上打开一个端口，并将该端口收到的流量重定向到基础服务.简言之，可以通过集群任意节点的IP+端口访问到该服务。</p>
<p>kubia-svc-nodeport.yaml</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">apiVersion: v1</span><br><span class="line">kind: Service</span><br><span class="line">metadata:</span><br><span class="line">    name: kubia</span><br><span class="line">spec:</span><br><span class="line">    #sessionAffinity: ClientIP</span><br><span class="line">    type: NodePort</span><br><span class="line">    ports:</span><br><span class="line">    - name: http</span><br><span class="line">      port: 80</span><br><span class="line">      targetPort: 8080</span><br><span class="line">      nodePort: 30123</span><br><span class="line">    selector:</span><br><span class="line">      run: kubia</span><br></pre></td></tr></table></figure>
<p>结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">root@node1:&#x2F;opt&#x2F;yaml&#x2F;demo# kubectl create -f kubia-svc-nodeport.yaml</span><br><span class="line">service&#x2F;kubia created</span><br><span class="line">root@node1:&#x2F;opt&#x2F;yaml&#x2F;demo# kubectl get svc</span><br><span class="line">NAME         TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)        AGE</span><br><span class="line">kubernetes   ClusterIP   10.96.0.1        &lt;none&gt;        443&#x2F;TCP        86m</span><br><span class="line">kubia        NodePort    10.102.109.144   &lt;none&gt;        80:30123&#x2F;TCP   4s</span><br></pre></td></tr></table></figure>

<p>如果这里不主动指定nodePort，Kubernetes将在指定的范围内分配端口（默认值：30000-32767）。</p>
<p><img src="http://assets.processon.com/chart_image/5c75503fe4b0f9fba693aa53.png" alt="外部客户端通过nodepord访问服务"></p>
<h3 id="2-将服务的类型设置成LoadBanance"><a href="#2-将服务的类型设置成LoadBanance" class="headerlink" title="2.将服务的类型设置成LoadBanance"></a>2.将服务的类型设置成LoadBanance</h3><p>负载均衡器拥有独一无二的可以公开访问的ip地址，并将所有连接重定向到服务，LoadBalancer一般都是公有云厂商提供，不需要自建。</p>
<p>此类型需要环境支持Load Badancer，否则不会调用负载均衡器，这时服务表现的像一个NodePort服务.因为Load Badancer是NodeProt服务的扩展。</p>
<p>kubia-svc-loadbalancer.yaml</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">apiVersion: v1</span><br><span class="line">kind: Service</span><br><span class="line">metadata:</span><br><span class="line">    name: kubia</span><br><span class="line">spec:</span><br><span class="line">    #sessionAffinity: ClientIP</span><br><span class="line">    type: LoadBalancer</span><br><span class="line">    ports:</span><br><span class="line">    - name: http</span><br><span class="line">      port: 80</span><br><span class="line">      targetPort: 8080</span><br><span class="line">      nodePort: 30123</span><br><span class="line">    selector:</span><br><span class="line">      run: kubia</span><br></pre></td></tr></table></figure>

<h3 id="3-创建一个Ingress资源"><a href="#3-创建一个Ingress资源" class="headerlink" title="3.创建一个Ingress资源"></a>3.创建一个Ingress资源</h3><p>为什么需要Ingress</p>
<ul>
<li><p>每个LoadBanalcer服务都需要自己的负载均衡器以及独有的共有IP，而Ingress只需要一个公网IP就能为许多服务提供访问。当客户端向Ingress发送HTTP请求时，Ingress会根据请求的主机名和路径决定请求转发到的服务。</p>
</li>
<li><p>Ingress在HTTP层工作，可以实现一些服务不能实现的功能，比如基于cookie的会话亲和性等。</p>
</li>
</ul>
<p><img src="http://assets.processon.com/chart_image/5c75517be4b0f0908aa32b64.png" alt="ingress"></p>
<p>只有Ingress控制器在集群中运行，Ingress资源才能正常工作。不同的K8s环境使用不同的控制器实现，但有些并不提供默认控制器。</p>
<p>Kubernetes 作为一个项目，目前支持和维护 AWS， GCE 和 nginx Ingress 控制器。</p>
<p>可以在集群中部署任意数量的 ingress 控制器。 创建 ingress 时，应该使用适当的 ingress.class 注解每个Ingress 以表明在集群中如果有多个 Ingress 控制器时，应该使用哪个 Ingress 控制器.如果不定义 ingress.class，云提供商可能使用默认的 Ingress 控制器.</p>
<h4 id="部署nginx-ingress控制器"><a href="#部署nginx-ingress控制器" class="headerlink" title="部署nginx ingress控制器"></a>部署nginx ingress控制器</h4><p>官网：<a href="https://kubernetes.github.io/ingress-nginx/deploy/" target="_blank" rel="noopener">https://kubernetes.github.io/ingress-nginx/deploy/</a></p>
<p>默认配置从所有名称空间监视Ingress对象。</p>
<p>若要更改此行为，请使用该标志–watch-namespace将范围限制为特定的名称空间。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F;下载mandatory.yaml</span><br><span class="line">wget https:&#x2F;&#x2F;github.com&#x2F;kubernetes&#x2F;ingress-nginx&#x2F;blob&#x2F;nginx-0.30.0&#x2F;deploy&#x2F;static&#x2F;mandatory.yaml</span><br><span class="line"></span><br><span class="line">root@node1:&#x2F;opt&#x2F;yaml&#x2F;demo# kubectl apply -f mandatory.yaml</span><br><span class="line">namespace&#x2F;ingress-nginx created</span><br><span class="line">configmap&#x2F;nginx-configuration created</span><br><span class="line">configmap&#x2F;tcp-services created</span><br><span class="line">configmap&#x2F;udp-services created</span><br><span class="line">serviceaccount&#x2F;nginx-ingress-serviceaccount created</span><br><span class="line">clusterrole.rbac.authorization.k8s.io&#x2F;nginx-ingress-clusterrole created</span><br><span class="line">role.rbac.authorization.k8s.io&#x2F;nginx-ingress-role created</span><br><span class="line">rolebinding.rbac.authorization.k8s.io&#x2F;nginx-ingress-role-nisa-binding created</span><br><span class="line">clusterrolebinding.rbac.authorization.k8s.io&#x2F;nginx-ingress-clusterrole-nisa-binding created</span><br><span class="line">deployment.apps&#x2F;nginx-ingress-controller created</span><br><span class="line">limitrange&#x2F;ingress-nginx created</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F;下载service-nodeport.yaml</span><br><span class="line">wget https:&#x2F;&#x2F;github.com&#x2F;kubernetes&#x2F;ingress-nginx&#x2F;blob&#x2F;nginx-0.30.0&#x2F;deploy&#x2F;static&#x2F;provider&#x2F;baremetal&#x2F;service-nodeport.yaml</span><br><span class="line">root@node1:&#x2F;opt&#x2F;yaml&#x2F;demo# kubectl apply -f service-nodeport.yaml</span><br><span class="line">service&#x2F;ingress-nginx created</span><br></pre></td></tr></table></figure>
<p>验证</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">root@node1:&#x2F;opt&#x2F;yaml&#x2F;demo# kubectl -n ingress-nginx get pods</span><br><span class="line">NAME                                        READY   STATUS    RESTARTS   AGE</span><br><span class="line">nginx-ingress-controller-7fcf8df75d-wbssz   1&#x2F;1     Running   0          96s</span><br><span class="line"></span><br><span class="line">root@node1:&#x2F;opt&#x2F;yaml&#x2F;demo# kubectl -n ingress-nginx get svc</span><br><span class="line">NAME            TYPE       CLUSTER-IP       EXTERNAL-IP   PORT(S)                      AGE</span><br><span class="line">ingress-nginx   NodePort   10.100.133.178   &lt;none&gt;        80:30327&#x2F;TCP,443:31783&#x2F;TCP   16s</span><br></pre></td></tr></table></figure>
<p>访问测试</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">root@node1:&#x2F;opt&#x2F;yaml&#x2F;demo# curl http:&#x2F;&#x2F;10.100.133.178</span><br><span class="line">&lt;html&gt;</span><br><span class="line">&lt;head&gt;&lt;title&gt;404 Not Found&lt;&#x2F;title&gt;&lt;&#x2F;head&gt;</span><br><span class="line">&lt;body&gt;</span><br><span class="line">&lt;center&gt;&lt;h1&gt;404 Not Found&lt;&#x2F;h1&gt;&lt;&#x2F;center&gt;</span><br><span class="line">&lt;hr&gt;&lt;center&gt;nginx&#x2F;1.17.8&lt;&#x2F;center&gt;</span><br><span class="line">&lt;&#x2F;body&gt;</span><br><span class="line">&lt;&#x2F;html&gt;</span><br></pre></td></tr></table></figure>
<h4 id="创建Ingress资源"><a href="#创建Ingress资源" class="headerlink" title="创建Ingress资源"></a>创建Ingress资源</h4><p>上面我们已经常见了Ingress控制器，并且验证运行，因此现在可以创建一个Ingress资源。</p>
<p>kubia-ingress.yaml</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">apiVersion: extensions&#x2F;v1beta1</span><br><span class="line">kind: Ingress</span><br><span class="line">metadata:</span><br><span class="line">  name: kubia</span><br><span class="line">spec:</span><br><span class="line">  rules:</span><br><span class="line">  - host: kubia.example.com</span><br><span class="line">  - http:</span><br><span class="line">      paths:</span><br><span class="line">      - path: &#x2F;</span><br><span class="line">        backend:</span><br><span class="line">          serviceName: kubia-nodeport</span><br><span class="line">          servicePort: 80</span><br></pre></td></tr></table></figure>
<p>创建</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">root@node1:&#x2F;opt&#x2F;yaml&#x2F;demo# kubectl apply -f kubia-ingress.yaml</span><br><span class="line">ingress.extensions&#x2F;kubia created</span><br></pre></td></tr></table></figure>

<p><img src="https://blog-pic-1254088127.picsh.myqcloud.com/k8s-ingress-yaml.png" alt="ingress-yaml"></p>
<p>获取Ingress的IP地址</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">root@node1:&#x2F;opt&#x2F;yaml&#x2F;demo# kubectl get ingresses</span><br><span class="line">NAME    HOSTS               ADDRESS          PORTS   AGE</span><br><span class="line">kubia   kubia.example.com   10.100.133.178   80      69s</span><br></pre></td></tr></table></figure>

<p>拿到Ingress的ip后，我们要确定在Ingress中配置的host（kubia.example.com）要指向Ingress的IP地址。</p>
<p>可以在DNS服务中将kubia.example.com解析为10.100.133.178，或者在/etc/hosts文件中加一行</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">10.100.133.178 kubia.example.com</span><br></pre></td></tr></table></figure>
<p>现在可以通过Ingress访问pod了</p>
<p><img src="http://assets.processon.com/chart_image/5c75503fe4b0f9fba693aa73.png" alt="ingress工作原理"></p>
<h1 id="RS"><a href="#RS" class="headerlink" title="RS"></a>RS</h1><p>pod代表Kubernetes中最小的部署单元，在实际场景，我们希望部署的资源可以自动保持运行，并且保持健康，要做到这一点我们几乎不会直接创建pod<br>，而是创建ReplicaSet（老版本是ReplicationController）或Deployment这样的资源，接着由它们来创建并管理实际的pod</p>
<h2 id="存活探针"><a href="#存活探针" class="headerlink" title="存活探针"></a>存活探针</h2><p>Kubernetes可以通过存活探针（liveness probe）检查容器是否还在运行。可以为pod中的每个容器单独指定探针，Kubernetes会定期执行探针，如果探测失败，将重启容器。</p>
<p>三种探针</p>
<ul>
<li>HTTP GET探针对容器的IP地址（指定端口和路径）执行HTTP GET请求。</li>
<li>TCP套接字探针尝试与容器指定端口建立TCP连接。如果连接建立成功，则探测成功。</li>
<li>Exec 探针在容器内执行任意命令，并检查命令的退出状态码，如果状态码是0，则探测成功。</li>
</ul>
<p>创建基于HTTP的存活探针</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">apiVersion: v1</span><br><span class="line">kind: Pod</span><br><span class="line">metadata:</span><br><span class="line">  name: kubia-liveness</span><br><span class="line">  namespace: qa</span><br><span class="line">spec:</span><br><span class="line">  containers:</span><br><span class="line">  - image: luksa&#x2F;kubia-unhealthy</span><br><span class="line">    name: kubia</span><br><span class="line">    livenessProbe:</span><br><span class="line">      httpGet:</span><br><span class="line">        path: &#x2F;</span><br><span class="line">        port: 8080</span><br></pre></td></tr></table></figure>
<p>这里就定义了一个http get存活探针</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">root@node1:&#x2F;opt&#x2F;yaml&#x2F;demo# kubectl apply -f kubia-pod.yaml</span><br><span class="line">pod&#x2F;kubia-liveness created</span><br><span class="line">root@node1:&#x2F;opt&#x2F;yaml&#x2F;demo# kubectl get pods -n qa</span><br><span class="line">NAME             READY   STATUS    RESTARTS   AGE</span><br><span class="line">kubia-liveness   1&#x2F;1     Running   1          2m7s</span><br></pre></td></tr></table></figure>
<p>kubia-unhealthy服务健康检查每调用5次就会失败一次，所以这里过2分钟会发现服务被重启过一次了。<br>通过kubectl describe pod 命令可以看到容器当期的状态，重启了多少此，上次被终止的原因等等。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">kubectl describe pod kubia-liveness</span><br></pre></td></tr></table></figure>

<p><img src="https://blog-pic-1254088127.picsh.myqcloud.com/k8s-health-http.png" alt="k8s-health-http"></p>
<p>我们还可以配置探针的delay（延迟）、timeout（超时）、period（周期）等,可以通过kubectl explain命令查看yaml详细配置说明</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">root@node1:&#x2F;opt&#x2F;yaml&#x2F;demo# kubectl explain pod.spec.containers.livenessProbe</span><br></pre></td></tr></table></figure>

<ul>
<li>initialDelaySeconds 表示容器启动后延迟多久进行检测，默认0，及容器启动后即开始检测。</li>
<li>timeoutSeconds 表示超时时间，超时未响应则检测失败</li>
<li>periodSeconds 表示多久检测一次</li>
</ul>
<p>在生成环境中运行的pod一定要定义一个存活探针。没有探针的话Kubernetes无法知道你的应用是否存活。</p>
<h2 id="就绪探针"><a href="#就绪探针" class="headerlink" title="就绪探针"></a>就绪探针</h2><p>与存活探针不同，如果容器没有通过准备检查，不会被终止或重启，但是该容器将从endpoint中移除，也就是不会有流量发送到改pod,注意当检测到pod恢复正常后会被重新添加到endpoint中。<br>就绪指针确保有问题的pod不会被访问到。</p>
<p>一定要定义就绪探针</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">readinessProbe:</span><br><span class="line">  failureThreshold: 3</span><br><span class="line">  httpGet:</span><br><span class="line">    path: &#x2F;actuator&#x2F;health</span><br><span class="line">    port: 8090</span><br><span class="line">    scheme: HTTP</span><br><span class="line">  initialDelaySeconds: 300</span><br><span class="line">  periodSeconds: 30</span><br><span class="line">  successThreshold: 1</span><br><span class="line">  timeoutSeconds: 3</span><br></pre></td></tr></table></figure>

<h2 id="ReplicaSet"><a href="#ReplicaSet" class="headerlink" title="ReplicaSet"></a>ReplicaSet</h2><p>ReplicaSet是一种Kubernetes资源，它可以确保pod始终保持运行状态，如果pod因为任何原因消失（比如节点从集群中消失，或者pod从节点中驱逐），<br>RS会注意缺少了pod，并创建代替。</p>
<p>一般而言RS旨在创建和管理一个pod 的多个副本，RS的工作是确保标签的数量始终与其标签选择器匹配，如果不匹配，rs将根据所需，采取适当的操作来协调pod 的数量。</p>
<p>RS由3部份组成</p>
<ul>
<li>label selector 标签选择器，用于确认rs作用域中有哪些pod</li>
<li>replica count 副本个数，指定运行的pod数量</li>
<li>pod template pod模板，用于创建新的pod副本</li>
</ul>
<p>RS可以轻松实现pod的水平伸缩</p>
<h2 id="创建ReplicaSet"><a href="#创建ReplicaSet" class="headerlink" title="创建ReplicaSet"></a>创建ReplicaSet</h2><p>kubia-rs.yaml</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">apiVersion: apps&#x2F;v1</span><br><span class="line">kind: ReplicaSet</span><br><span class="line">metadata:</span><br><span class="line">  name: kubia</span><br><span class="line">  labels:</span><br><span class="line">    run: kubia</span><br><span class="line">spec:</span><br><span class="line">  # modify replicas according to your case</span><br><span class="line">  replicas: 3</span><br><span class="line">  selector:</span><br><span class="line">    matchLabels:</span><br><span class="line">      run: kubia</span><br><span class="line">  template:</span><br><span class="line">    metadata:</span><br><span class="line">      labels:</span><br><span class="line">        run: kubia</span><br><span class="line">    spec:</span><br><span class="line">      containers:</span><br><span class="line">      - name: kubia</span><br><span class="line">        image: luksa&#x2F;kubia</span><br></pre></td></tr></table></figure>
<p><img src="https://blog-pic-1254088127.picsh.myqcloud.com/k8s-rs-01.png" alt="k8s-rs"></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">root@node1:&#x2F;opt&#x2F;yaml&#x2F;demo# kubectl create -f kubia-rs.yaml</span><br><span class="line">replicaset.apps&#x2F;kubia created</span><br><span class="line">root@node1:&#x2F;opt&#x2F;yaml&#x2F;demo# kubectl get pods -o wide --show-labels</span><br><span class="line">NAME          READY   STATUS    RESTARTS   AGE     IP             NODE    NOMINATED NODE   READINESS GATES   LABELS</span><br><span class="line">kubia-f5vv9   1&#x2F;1     Running   0          3m48s   192.169.1.10   node2   &lt;none&gt;           &lt;none&gt;            run&#x3D;kubia</span><br><span class="line">kubia-qd2sl   1&#x2F;1     Running   0          3m48s   192.169.2.37   node3   &lt;none&gt;           &lt;none&gt;            run&#x3D;kubia</span><br><span class="line">kubia-t7krn   1&#x2F;1     Running   0          2m40s   192.169.1.11   node2   &lt;none&gt;           &lt;none&gt;            run&#x3D;kubia</span><br></pre></td></tr></table></figure>
<h2 id="模拟节点故障"><a href="#模拟节点故障" class="headerlink" title="模拟节点故障"></a>模拟节点故障</h2><p>下面我们模拟一个节点故障，从网络中端口其中一个节点，使用sudo ifconfig eth0 down 关闭器网络接口。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"># 关闭node2的网络</span><br><span class="line">root@node2:&#x2F;home&#x2F;richey# ifconfig ens33 down</span><br><span class="line"># 这时候node2节点已经NotReady不可用了 </span><br><span class="line">root@node1:&#x2F;opt&#x2F;yaml&#x2F;demo# kubectl get nodes</span><br><span class="line">NAME    STATUS     ROLES    AGE   VERSION</span><br><span class="line">node1   Ready      master   11d   v1.15.2</span><br><span class="line">node2   NotReady   &lt;none&gt;   11d   v1.15.2</span><br><span class="line">node3   Ready      &lt;none&gt;   11d   v1.15.2</span><br><span class="line"></span><br><span class="line"># kubernetes在重新调用pod之前会等待一段时间（如果节点因为网络原因或kubelet重新启动而无法访问）。大概过了几分钟后node2节点上的rs才重新在其它节点启动新的pod</span><br><span class="line">root@node1:&#x2F;opt&#x2F;yaml&#x2F;demo# kubectl get pods -o wide --show-labels</span><br><span class="line">NAME          READY   STATUS        RESTARTS   AGE   IP             NODE    NOMINATED NODE   READINESS GATES   LABELS</span><br><span class="line">kubia-2fssn   1&#x2F;1     Running       0          29s   192.169.2.39   node3   &lt;none&gt;           &lt;none&gt;            run&#x3D;kubia</span><br><span class="line">kubia-f5vv9   1&#x2F;1     Terminating   0          13m   192.169.1.10   node2   &lt;none&gt;           &lt;none&gt;            run&#x3D;kubia</span><br><span class="line">kubia-jjnjw   1&#x2F;1     Running       0          29s   192.169.2.40   node3   &lt;none&gt;           &lt;none&gt;            run&#x3D;kubia</span><br><span class="line">kubia-qd2sl   1&#x2F;1     Running       0          13m   192.169.2.37   node3   &lt;none&gt;           &lt;none&gt;            run&#x3D;kubia</span><br><span class="line">kubia-t7krn   1&#x2F;1     Terminating   0          12m   192.169.1.11   node2   &lt;none&gt;           &lt;none&gt;            run&#x3D;kubia</span><br></pre></td></tr></table></figure>

<p>可以通过修改pod的标签让其脱离rs的控制，但是注意当我们修改 一个pod的标签时，rs将发现其管理的pod的数量变少，会新创建一个。</p>
<h2 id="修改pod模板"><a href="#修改pod模板" class="headerlink" title="修改pod模板"></a>修改pod模板</h2><p>rs的pod模板可以随时改，但是它只会影响改之后的pod，对以创建的pod无影响。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">root@node1:&#x2F;opt&#x2F;yaml&#x2F;demo# kubectl get rs</span><br><span class="line">NAME    DESIRED   CURRENT   READY   AGE</span><br><span class="line">kubia   3         3         3       27m</span><br><span class="line">root@node1:&#x2F;opt&#x2F;yaml&#x2F;demo# kubectl edit rs kubia</span><br><span class="line">\replicaset.extensions&#x2F;kubia edited</span><br></pre></td></tr></table></figure>

<h2 id="水平缩放pod"><a href="#水平缩放pod" class="headerlink" title="水平缩放pod"></a>水平缩放pod</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">root@node1:&#x2F;opt&#x2F;yaml&#x2F;demo# kubectl scale rs kubia --replicas&#x3D;10</span><br><span class="line">replicaset.extensions&#x2F;kubia scaled</span><br><span class="line">root@node1:&#x2F;opt&#x2F;yaml&#x2F;demo# kubectl get pods -o wide</span><br><span class="line">NAME          READY   STATUS              RESTARTS   AGE    IP             NODE    NOMINATED NODE   READINESS GATES</span><br><span class="line">kubia-5kgwl   0&#x2F;1     ContainerCreating   0          3s     &lt;none&gt;         node3   &lt;none&gt;           &lt;none&gt;</span><br><span class="line">kubia-6tr6n   1&#x2F;1     Running             0          2m7s   192.169.2.44   node3   &lt;none&gt;           &lt;none&gt;</span><br><span class="line">kubia-96hqx   0&#x2F;1     ContainerCreating   0          3s     &lt;none&gt;         node3   &lt;none&gt;           &lt;none&gt;</span><br><span class="line">kubia-bs7ft   1&#x2F;1     Running             0          2m7s   192.169.1.16   node2   &lt;none&gt;           &lt;none&gt;</span><br><span class="line">kubia-dhsh8   0&#x2F;1     ContainerCreating   0          3s     &lt;none&gt;         node3   &lt;none&gt;           &lt;none&gt;</span><br><span class="line">kubia-gk67n   0&#x2F;1     ContainerCreating   0          3s     &lt;none&gt;         node2   &lt;none&gt;           &lt;none&gt;</span><br><span class="line">kubia-h2srg   0&#x2F;1     ContainerCreating   0          3s     &lt;none&gt;         node2   &lt;none&gt;           &lt;none&gt;</span><br><span class="line">kubia-png2f   1&#x2F;1     Running             0          2m7s   192.169.1.17   node2   &lt;none&gt;           &lt;none&gt;</span><br><span class="line">kubia-w9pnp   0&#x2F;1     ContainerCreating   0          3s     &lt;none&gt;         node3   &lt;none&gt;           &lt;none&gt;</span><br><span class="line">kubia-xqlwh   0&#x2F;1     ContainerCreating   0          3s     &lt;none&gt;         node2   &lt;none&gt;           &lt;none&gt;</span><br></pre></td></tr></table></figure>

<h2 id="删除rs"><a href="#删除rs" class="headerlink" title="删除rs"></a>删除rs</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">root@node1:&#x2F;opt&#x2F;yaml&#x2F;demo# kubectl get pods</span><br><span class="line">NAME          READY   STATUS    RESTARTS   AGE</span><br><span class="line">kubia-5kgwl   1&#x2F;1     Running   0          2m42s</span><br><span class="line">kubia-6tr6n   1&#x2F;1     Running   0          4m46s</span><br><span class="line">kubia-96hqx   1&#x2F;1     Running   0          2m42s</span><br><span class="line">kubia-bs7ft   1&#x2F;1     Running   0          4m46s</span><br><span class="line">kubia-dhsh8   1&#x2F;1     Running   0          2m42s</span><br><span class="line">kubia-gk67n   1&#x2F;1     Running   0          2m42s</span><br><span class="line">kubia-h2srg   1&#x2F;1     Running   0          2m42s</span><br><span class="line">kubia-png2f   1&#x2F;1     Running   0          4m46s</span><br><span class="line">kubia-w9pnp   1&#x2F;1     Running   0          2m42s</span><br><span class="line">kubia-xqlwh   1&#x2F;1     Running   0          2m42s</span><br><span class="line">root@node1:&#x2F;opt&#x2F;yaml&#x2F;demo# kubectl delete rs kubia</span><br><span class="line">replicaset.extensions &quot;kubia&quot; deleted</span><br><span class="line">root@node1:&#x2F;opt&#x2F;yaml&#x2F;demo# kubectl get pods</span><br><span class="line">NAME          READY   STATUS        RESTARTS   AGE</span><br><span class="line">kubia-5kgwl   1&#x2F;1     Terminating   0          2m59s</span><br><span class="line">kubia-6tr6n   1&#x2F;1     Terminating   0          5m3s</span><br><span class="line">kubia-96hqx   1&#x2F;1     Terminating   0          2m59s</span><br><span class="line">kubia-bs7ft   1&#x2F;1     Terminating   0          5m3s</span><br><span class="line">kubia-dhsh8   1&#x2F;1     Terminating   0          2m59s</span><br><span class="line">kubia-gk67n   1&#x2F;1     Terminating   0          2m59s</span><br><span class="line">kubia-h2srg   1&#x2F;1     Terminating   0          2m59s</span><br><span class="line">kubia-png2f   1&#x2F;1     Terminating   0          5m3s</span><br><span class="line">kubia-w9pnp   1&#x2F;1     Terminating   0          2m59s</span><br><span class="line">kubia-xqlwh   1&#x2F;1     Terminating   0          2m59s</span><br></pre></td></tr></table></figure>
<p>删除rs后，rs管理的pod也会被删除,要想删除rc保持pod运行，可以加参数–cascade=false</p>
<h2 id="rs丰富的标签选择器"><a href="#rs丰富的标签选择器" class="headerlink" title="rs丰富的标签选择器"></a>rs丰富的标签选择器</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">root@node1:&#x2F;opt&#x2F;yaml&#x2F;demo# kubectl explain rs.spec.selector</span><br><span class="line">...</span><br><span class="line">FIELDS:</span><br><span class="line">   matchExpressions	&lt;[]Object&gt;</span><br><span class="line"></span><br><span class="line">   matchLabels	&lt;map[string]string&gt;</span><br><span class="line">...</span><br></pre></td></tr></table></figure>
<p>可以看到selector有两种配置方式，matchLabels可以配置键值对的label，而matchExpressions有更丰富的表达力。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">selector:</span><br><span class="line">  matchExpressions:</span><br><span class="line">    - key: app</span><br><span class="line">      operator: In</span><br><span class="line">      values:</span><br><span class="line">        - kubia</span><br></pre></td></tr></table></figure>

<p>可以设置多个表达式，每个表达式都必须包含一个key，一个operator，并且可能还有一个value的列表（取决于运算符）。</p>
<p>有4种有效的运算符：</p>
<ul>
<li>In Label的值必须与其中一个values值匹配</li>
<li>NotIn Label的值与任何指定的values值不匹配 </li>
<li>Exists pod必须包含一个指定名称的标签（值不重要）。使用此运算符，不应该指定values值</li>
<li>DoesNotExist pod不得包含有指定名称的标签。使用此运算符，不应该指定values值</li>
</ul>
<p>如果指定了多个表达式，则这些表达式必须都满足才能匹配。</p>
<h1 id="DaemonSet"><a href="#DaemonSet" class="headerlink" title="DaemonSet"></a>DaemonSet</h1><h1 id="Job"><a href="#Job" class="headerlink" title="Job"></a>Job</h1>
      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.png" alt="Richey Liu 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.jpg" alt="Richey Liu 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    Richey Liu
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://10000hours.top/2021/05/12/Kubernetes02-%E6%A0%B8%E5%BF%83%E6%A6%82%E5%BF%B5/" title="Kubernetes02-核心概念">http://10000hours.top/2021/05/12/Kubernetes02-%E6%A0%B8%E5%BF%83%E6%A6%82%E5%BF%B5/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/K8s/" rel="tag"># K8s</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2021/05/06/Kubernetes01-%E5%91%BD%E4%BB%A4%E9%80%9F%E6%9F%A5/" rel="next" title="Kubernetes01-命令速查">
                <i class="fa fa-chevron-left"></i> Kubernetes01-命令速查
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2021/05/24/Kubernetes03-%E9%9B%86%E7%BE%A4%E6%90%AD%E5%BB%BA/" rel="prev" title="Kubernetes03-集群搭建">
                Kubernetes03-集群搭建 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        
<script>
  with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='//bdimg.share.baidu.com/static/api/js/share.js?cdnversion='+~(-new Date()/36e5)];
</script>

      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/avatar.jpg"
                alt="Richey Liu" />
            
              <p class="site-author-name" itemprop="name">Richey Liu</p>
              <p class="site-description motion-element" itemprop="description">花有重开时人无再少年</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives">
              
                  <span class="site-state-item-count">131</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">24</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">42</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/liubaolin" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-globe"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="brin.baolin@gmail.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-globe"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#比较容器和虚拟机"><span class="nav-number">1.</span> <span class="nav-text">比较容器和虚拟机</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Pod"><span class="nav-number">2.</span> <span class="nav-text">Pod</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#区别于容器"><span class="nav-number">2.1.</span> <span class="nav-text">区别于容器</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#平坦pod间网络"><span class="nav-number">2.2.</span> <span class="nav-text">平坦pod间网络</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#yaml文件重要参数"><span class="nav-number">2.3.</span> <span class="nav-text">yaml文件重要参数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#以YAML或JSON描述文件船舰pod"><span class="nav-number">2.4.</span> <span class="nav-text">以YAML或JSON描述文件船舰pod</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#访问pod"><span class="nav-number">2.5.</span> <span class="nav-text">访问pod</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#服务"><span class="nav-number">3.</span> <span class="nav-text">服务</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#列出所有服务"><span class="nav-number">3.1.</span> <span class="nav-text">列出所有服务</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#通过kubectl-expose创建服务"><span class="nav-number">3.2.</span> <span class="nav-text">通过kubectl expose创建服务</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#通过YAML描述文件创建服务"><span class="nav-number">3.3.</span> <span class="nav-text">通过YAML描述文件创建服务</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#在已有的pod中运行命令请求service"><span class="nav-number">3.4.</span> <span class="nav-text">在已有的pod中运行命令请求service</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#设置服务上的会话亲和性"><span class="nav-number">3.5.</span> <span class="nav-text">设置服务上的会话亲和性</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#同一个服务暴露多个端口"><span class="nav-number">3.6.</span> <span class="nav-text">同一个服务暴露多个端口</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#服务发现"><span class="nav-number">3.7.</span> <span class="nav-text">服务发现</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#通过环境变量发现服务"><span class="nav-number">3.7.1.</span> <span class="nav-text">通过环境变量发现服务</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#通过DNS发现服务"><span class="nav-number">3.7.2.</span> <span class="nav-text">通过DNS发现服务</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#通过FQDN（全限定域名）连接服务"><span class="nav-number">3.7.3.</span> <span class="nav-text">通过FQDN（全限定域名）连接服务</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#无法ping通服务ip"><span class="nav-number">3.7.4.</span> <span class="nav-text">无法ping通服务ip</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#endpoint-可解决访问集群外服务"><span class="nav-number">3.8.</span> <span class="nav-text">endpoint(可解决访问集群外服务)</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#手动配置endpoint（访问外部服务的方法1）"><span class="nav-number">3.8.1.</span> <span class="nav-text">手动配置endpoint（访问外部服务的方法1）</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#为外部服务创建别名（访问外部服务的方法2）"><span class="nav-number">3.8.2.</span> <span class="nav-text">为外部服务创建别名（访问外部服务的方法2）</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Service-type类型"><span class="nav-number">3.9.</span> <span class="nav-text">Service type类型</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#ClusterIP"><span class="nav-number">3.9.1.</span> <span class="nav-text">ClusterIP</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-将服务的类型设置成NodePort"><span class="nav-number">3.9.2.</span> <span class="nav-text">1.将服务的类型设置成NodePort</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-将服务的类型设置成LoadBanance"><span class="nav-number">3.9.3.</span> <span class="nav-text">2.将服务的类型设置成LoadBanance</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-创建一个Ingress资源"><span class="nav-number">3.9.4.</span> <span class="nav-text">3.创建一个Ingress资源</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#部署nginx-ingress控制器"><span class="nav-number">3.9.4.1.</span> <span class="nav-text">部署nginx ingress控制器</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#创建Ingress资源"><span class="nav-number">3.9.4.2.</span> <span class="nav-text">创建Ingress资源</span></a></li></ol></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#RS"><span class="nav-number">4.</span> <span class="nav-text">RS</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#存活探针"><span class="nav-number">4.1.</span> <span class="nav-text">存活探针</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#就绪探针"><span class="nav-number">4.2.</span> <span class="nav-text">就绪探针</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#ReplicaSet"><span class="nav-number">4.3.</span> <span class="nav-text">ReplicaSet</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#创建ReplicaSet"><span class="nav-number">4.4.</span> <span class="nav-text">创建ReplicaSet</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#模拟节点故障"><span class="nav-number">4.5.</span> <span class="nav-text">模拟节点故障</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#修改pod模板"><span class="nav-number">4.6.</span> <span class="nav-text">修改pod模板</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#水平缩放pod"><span class="nav-number">4.7.</span> <span class="nav-text">水平缩放pod</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#删除rs"><span class="nav-number">4.8.</span> <span class="nav-text">删除rs</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#rs丰富的标签选择器"><span class="nav-number">4.9.</span> <span class="nav-text">rs丰富的标签选择器</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#DaemonSet"><span class="nav-number">5.</span> <span class="nav-text">DaemonSet</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Job"><span class="nav-number">6.</span> <span class="nav-text">Job</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2015 &mdash; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Richey Liu</span>

  
</div>






  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: false,
        appId: 'espIarB7yj7vR1el85iiMLjb-gzGzoHsz',
        appKey: 'v35zFd1Yc4PX5KsGn2wHgrob',
        placeholder: '欢迎留言！',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
  </script>



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("98BykxDu7C0UsRu0zaggGlMu-gzGzoHsz", "a21Q7nym42YYGdxdx2XxxQNM");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
